package org.flowcircuit.model


import appearance.DrawContext
import board.{Socket, Board}
import component.Component
import coordinates.Pos
import java.awt.Graphics2D
import utils.CallbackList

/**
 * 
 * 
 * @author Hans Haggstrom
 */

class Circuit() {

  val boards = CallbackList[Board]()

  def getElementAtPosition( queryPos : Pos, context : DrawContext  ) : Option[CircuitElement] = {
    boards foreach { board : Board =>
      board.getElementAtPosition( queryPos, context ) match {
        case Some(x) => return Some(x)
        case None => // fallthrough to next board
      }
    }
    
    None
  }

  def getNearestSocket( queryPos : Pos, context : DrawContext  ) : Option[Socket] = {
    val allSockets : List[Socket] = boards.flatten{ _.sockets.list }

    val notFOundPair = (Math.POS_INF_FLOAT, null.asInstanceOf[Socket] )
    val nearest = allSockets.foldLeft( notFOundPair ){ (nearest : (Float, Socket), socket : Socket) =>
      val squaredDistance = queryPos.squaredDistance( socket.pos )       
      if ( squaredDistance < nearest._1 ) (squaredDistance, socket)
      else nearest
    }

    if ( nearest._2 != null ) Some[Socket](nearest._2)
    else None
  }

  def render( context : DrawContext ) {

    // Render any ground plane (grid etc)
    // TODO

    // Render each board
    boards foreach ( _.render( context ) )
  }

}